package com.studymaster.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.studymaster.domain.Event;
import com.studymaster.service.EventService;
import com.studymaster.util.Escape;
import com.studymaster.util.JsonHelper;
@Controller 
public class DownLoad {

	@RequestMapping(value = "/loadDb.do")
	public ResponseEntity<byte[]> loadDb(HttpServletRequest request) throws IOException{

		String pathString=request.getRealPath("/download/server.db");
		System.out.println(pathString);
		byte[] ret = null;
		HttpHeaders responseHeaders=null;
		File file = new File(pathString);  
		FileInputStream in=null;
		ByteArrayOutputStream  out=null;
		try {
			in = new FileInputStream(file);
			out= new ByteArrayOutputStream(1024); 
			responseHeaders = httpHeaderExcelFileAttachment(file.getName(),file.length());
			byte[] b = new byte[1024];  
			int len = 0;  
			while ((len = in.read(b)) != -1) {  
				out.write(b, 0, len);  
			}  
			ret=out.toByteArray();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if(out!=null)
				out.close();
			if(in!=null)
				in.close(); 
		}
		
	 return new ResponseEntity<byte[]>(ret,
                responseHeaders, HttpStatus.OK);
	}
	public static HttpHeaders httpHeaderExcelFileAttachment(final String fileName,
	        final long lenthl) {
	    String encodedFileName = fileName.replace('"', ' ').replace(' ', '_');
	    //encodedFileName=Escape.gbEncoding(encodedFileName);
	    HttpHeaders responseHeaders = new HttpHeaders();
	    responseHeaders.setContentType(MediaType.parseMediaType("Application/x-download;charset=utf-8"));                     ///application/vnd.ms-excel
	    responseHeaders.setContentLength(lenthl);
	 //   responseHeaders.set("Content-Disposition", "attachment");
	    responseHeaders.add("Content-Disposition", "filename=\"" + encodedFileName + '\"');
	    return responseHeaders;
	}
}
